package com.example.spring.thread.lock.rw;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: orange
 * @create: 2023-08-08 12:07
 * @description: 可重入锁
 */
public class ReentrantLockMain {

    public static final List<Integer> noLock = new ArrayList<>();
    public static final List<Integer> lock = new ArrayList<>();
    private static final ReentrantLock reentrant = new ReentrantLock();

    public static void threadNoLock() throws InterruptedException {
        int size = 30000;
        Thread[] threads = new Thread[size];
        for (int i = 0; i < size; i++) {
            Thread t = new Thread(() -> {
                noLock.add(1);
            });
            threads[i] = t;
            t.start();
        }

        for (int i = 0; i < threads.length; i++) {
            threads[i].join();
        }
    }


    private static void thread() throws InterruptedException {
        int size = 30000;
        Thread[] threads = new Thread[size];
        for (int i = 0; i < size; i++) {
            Thread t = new Thread(() -> {
               try {
                   reentrant.lock();
                   lock.add(1);
               } finally {
                   reentrant.unlock();
               }
            });
            threads[i] = t;
            t.start();
        }

        for (int i = 0; i < threads.length; i++) {
            threads[i].join();
        }
    }

    public static void main(String[] args) {
        try {
            threadNoLock();
            System.out.format("no lock %d \n", noLock.size());
            thread();
            System.out.format("lock %d ", lock.size());
        } catch (InterruptedException interruptedException) {
            interruptedException.printStackTrace();
        }
    }

}
